package Concurrent;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description：
 * Author: zhangc
 * Date：2017/9/29 19:06
 */
public class WaitNotify {

    private static Queue<Integer> queue = new LinkedList<>();
    private static AtomicInteger atomicInteger = new AtomicInteger(0);


    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(10, new ThreadFactory());
        for (int i = 0; i < 10; i++) {
            service.execute(new Producer());
            if (i % 8 == 3)
                service.execute(new Consumer());
        }
    }


    public static void produce() throws InterruptedException {
        synchronized (queue) {
            try {
                while (queue.size() == 20)
                    queue.wait();
                int i = atomicInteger.incrementAndGet();
                queue.add(i);
                System.out.println(Thread.currentThread().getName() + " : " + "生产者生产了一个产品：" + i);
            } finally {
                queue.notifyAll();
            }
        }
    }

    public static void consumer() throws InterruptedException {
        synchronized (queue) {
            try {
                while (queue.isEmpty()) {
                    queue.wait();
                }
                Integer remove = queue.remove();
                System.out.println(Thread.currentThread().getName() + " : " + "消费者消费了一个产品：" + remove);
            } finally {
                queue.notifyAll();
            }
        }
    }
}


class ProducerWait implements Runnable {

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                WaitNotify.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class ConsumerWait implements Runnable {

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            try {
                WaitNotify.consumer();
            } catch (InterruptedException e) {
            }
        }
    }
}
